﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using TuKu.Load;
using System.Threading;
using System.IO;
using TuKu.Common;
using System.Configuration;


namespace TuKu
{
    public partial class TopicList : Form
    {
        string webpath = System.Configuration.ConfigurationManager.AppSettings["webpath"];
        string templatepath = ConfigurationManager.AppSettings["templatepath"];

        bool wselected = false;
        Point p = new Point();
        int driftX = 0, driftY = 0;
        int mx = 0, my = 0;
        // 引用API

        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
        public static extern bool BitBlt(
         IntPtr hdcDest, //目标设备的句柄 
         int nXDest, // 目标对象的左上角的X坐标 
         int nYDest, // 目标对象的左上角的X坐标 
         int nWidth, // 目标对象的矩形的宽度 
         int nHeight, // 目标对象的矩形的长度 
         IntPtr hdcSrc, // 源设备的句柄 
         int nXSrc, // 源对象的左上角的X坐标 
         int nYSrc, // 源对象的左上角的X坐标 
         System.Int32 dwRop // 光栅的操作值 
         );
        public TopicList()
        {
            InitializeComponent();
        }

        private void combGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            int groupid = int.Parse(new BLL.Group().GetModel(combGroup.Text).ID.ToString());
            DataBindClass.subGroupBind(groupid,listsubGroup);
            label1.Text = listsubGroup.Items.Count.ToString();
        }
        private void TopicList_Load(object sender, EventArgs e)
        {
            DataBindClass.GroupBind(combGroup);
        }
        private void listsubGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            int subGroupid = int.Parse(new BLL.subGroup().GetModel(listsubGroup.Text).ID.ToString());
            listTopic.Items.Clear();
            DataTable dt = new BLL.Topic().GetList(" subGroupid=" + subGroupid).Tables[0];
            foreach (DataRow dr in dt.Rows)
            {
                listTopic.Items.Add(dr["body"].ToString().Trim());
            }
            label2.Text = listTopic.Items.Count.ToString();

        }
        private void listTopic_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string p = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
            //Regex re = new Regex(p, RegexOptions.IgnoreCase);
            //MatchCollection mc = re.Matches(this.listTopic.Text);
            //if (mc.Count > 0)
            //{
            //    this.imgShow.Image = Image.FromStream(System.Net.WebRequest.Create(listTopic.Text).GetResponse().GetResponseStream());
            //    lblimgsize.Text = "尺寸:" + imgShow.Image.Size.Width.ToString() + "*" + imgShow.Image.Size.Height.ToString();

            //}
            //else
            //{
            //    imgShow.Image = null;
            //}
            imgShow.Image =Image.FromFile(listTopic.Text);
        }
        #region 拖放处理
        private void imgShow_MouseDown(object sender, MouseEventArgs e)
        {
            wselected = true;
            p.X = e.X;
            p.Y = e.Y;
        }
        private void imgShow_MouseMove(object sender, MouseEventArgs e)
        {
            if (wselected)
            {
                driftX = p.X - e.X;
                driftY = p.Y - e.Y;
                mx = mx - driftX;
                my = my - driftY;
                Bitmap bm = new Bitmap(this.imgShow.Image);
                Graphics g = imgShow.CreateGraphics();
                g.Clear(imgShow.BackColor);
                g.DrawImage(bm, mx, my);

                p.X = e.X;
                p.Y = e.Y;

                bm.Dispose();
                g.Dispose();
                label3.Text = imgShow.Image.Height.ToString() + "," + imgShow.Width.ToString();

                label3.Refresh();

            }
        }
        private void imgShow_MouseUp(object sender, MouseEventArgs e)
        {
            wselected = false;
        }
        #endregion

        #region 图片切割
        private void btnMake_Click(object sender, EventArgs e)
        {
            Point p = imgShow.PointToScreen(imgShow.Bounds.Location);
            p.Y -= imgShow.Top;
            p.X -= imgShow.Left;
            Rectangle area = new Rectangle(p, new Size(imgShow.Width, imgShow.Height));
            int left = area.Left;
            int right = area.Right;
            int top = area.Top;
            int bottom = area.Bottom;
            if (left < Screen.PrimaryScreen.Bounds.Left)
            { left = Screen.PrimaryScreen.Bounds.Left; }
            if (right > Screen.PrimaryScreen.Bounds.Right)
            { right = Screen.PrimaryScreen.Bounds.Right; }
            if (top < Screen.PrimaryScreen.Bounds.Top)
            { top = Screen.PrimaryScreen.Bounds.Top; }
            if (bottom > Screen.PrimaryScreen.Bounds.Bottom)
            { bottom = Screen.PrimaryScreen.Bounds.Bottom; }
            area.X = left;
            area.Y = top;
            area.Width = right - left;
            area.Height = bottom - top;
            Bitmap bm = new Bitmap(windowFullScreen());
            Image img = bm.Clone(area, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
//            save(img);
            string path = PathClass.webpath + "\\" + combGroup.Text.toQuanPin() + "\\" + listsubGroup.Text.toQuanPin();

            if (!Directory.Exists(path))
            {
                FileManager.CreateFoler(path);
            
            }
            System.Drawing.Imaging.ImageFormat imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
            string fileExtend = listTopic.SelectedItem.ToString().getFileExtends().ToLower();
            switch (fileExtend)
            {
                case "jpg":
                    imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case "gif":
                    imgformat = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                default:
                    imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
            }
            img.Save(path + "\\logo." + fileExtend, imgformat);
        }
        private void save(Image img)
        {
            bool isSave = true;
            SaveFileDialog saveImageDialog = new SaveFileDialog();
            saveImageDialog.Title = "Capture screen image save dialog";
            //////////////////////////“文本文件(*.txt)|*.txt|所有文件(*.*)|*.*”
            saveImageDialog.Filter = "GIFs(*.gif)|*.gif|JPEGs(*.jpg)|*.jpg;*.jpeg";

            if (saveImageDialog.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveImageDialog.FileName.ToString();

                if (fileName != "" && fileName != null)
                {
                    string fileExtName = fileName.Substring(fileName.LastIndexOf(".") + 1).ToString();

                    System.Drawing.Imaging.ImageFormat imgformat = null;

                    if (fileExtName != "")
                    {
                        switch (fileExtName)
                        {
                            case "jpg":
                                imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                                break;
                            case "bmp":
                                imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
                                break;
                            case "gif":
                                imgformat = System.Drawing.Imaging.ImageFormat.Gif;
                                break;
                            default:
                                MessageBox.Show("只能存取为: jpg,bmp,gif 格式");
                                isSave = false;
                                break;
                        }

                    }

                    //默认保存为JPG格式
                    if (imgformat == null)
                    {
                        imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
                    }

                    if (isSave)
                    {
                        try
                        {
                            img.Save(fileName, imgformat);
                            MessageBox.Show("图片已经成功保存!~~");
                        }
                        catch
                        {
                            MessageBox.Show("保存失败,你还没有截取过图片或已经清空图片!");
                        }
                    }

                }

            }
        }
        public Bitmap windowFullScreen()
        {
            //建立屏幕Graphics
            Graphics grpScreen = Graphics.FromHwnd(IntPtr.Zero);
            //根据屏幕大小建立位图
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, grpScreen);
            //建立位图相关Graphics
            Graphics grpBitmap = Graphics.FromImage(bitmap);
            //建立屏幕上下文
            IntPtr hdcScreen = grpScreen.GetHdc();
            //建立位图上下文
            IntPtr hdcBitmap = grpBitmap.GetHdc();
            //将屏幕捕获保存在图位中
            BitBlt(hdcBitmap, 0, 0, bitmap.Width, bitmap.Height, hdcScreen, 0, 0, 0x00CC0020);
            //关闭位图句柄
            grpBitmap.ReleaseHdc(hdcBitmap);
            //关闭屏幕句柄
            grpScreen.ReleaseHdc(hdcScreen);
            //释放位图对像
            grpBitmap.Dispose();
            //释放屏幕对像
            grpScreen.Dispose();

            //返回捕获位图
            return bitmap;
        }

        #endregion

        private void btnWaterMark_Click(object sender, EventArgs e)
        {
            LoadingHandler.Show(this, args =>
            {
                foreach (string str in this.listTopic.Items)
                {
                    string newFileName = "new_" + Common.FileManager.GetFileName(str);
                    Common.WaterMark.AddImageSignPic(Image.FromFile(str), str.Replace(Common.FileManager.GetFileName(str), newFileName), System.Configuration.ConfigurationManager.AppSettings["watermark"].ToString(), 9, 100,5);
                    Thread.Sleep(50);
                }
            });
        }

        private void btnMakeListPage_Click(object sender, EventArgs e)
        {
            string subName = listsubGroup.SelectedItem.ToString();
            if (!String.IsNullOrEmpty(subName))
            {
               
                int subGroupid =int.Parse(new BLL.subGroup().GetModel(subName).ID.ToString());
                DataTable dt = new BLL.Topic().GetList(" subGroupid = " + subGroupid).Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    
                }
            }
           
           
        }
    }

}
